package com.wjs.gulimall.gulimallorder.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.wjs.gulimall.gulimallorder.constant.OrderConstant;
import com.wjs.gulimall.gulimallorder.dao.OrderItemDao;
import com.wjs.gulimall.gulimallorder.entity.OrderItemEntity;
import com.wjs.gulimall.gulimallorder.entity.PaymentInfoEntity;
import com.wjs.gulimall.gulimallorder.enums.OrderStatusEnum;
import com.wjs.gulimall.gulimallorder.feigin.CartFeignService;
import com.wjs.gulimall.gulimallorder.feigin.MemberFeignService;
import com.wjs.gulimall.gulimallorder.feigin.ProductFeignService;
import com.wjs.gulimall.gulimallorder.feigin.WareFeginService;
import com.wjs.gulimall.gulimallorder.interceptor.LoginUserInterceptor;
import com.wjs.gulimall.gulimallorder.service.OrderItemService;
import com.wjs.gulimall.gulimallorder.service.PaymentInfoService;
import com.wjs.gulimall.gulimallorder.to.OrderCreateTo;
import com.wjs.gulimall.gulimallorder.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.wjs.gulimall.gulimallorder.dao.OrderDao;
import com.wjs.gulimall.gulimallorder.entity.OrderEntity;
import com.wjs.gulimall.gulimallorder.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> threadLocal=new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeginService wareFeginService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor executor;
    
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 给订单确认页返回应该有的数据
     * @return
     */
    @Override
    public OrderConfrimVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfrimVo confrimVo=new OrderConfrimVo();
        //从ThreadLocal获取当前登录人信息
        MemberRespVo member = LoginUserInterceptor.loginUser.get();
        //异步任务开始之前拿到原请求数据，解决异步下Feign接口请求头丢失问题
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //异步任务一
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //远程接口掉用之前设置请求原数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(member.getId());
            confrimVo.setAddress(address);
        }, executor);
        //异步任务二
        CompletableFuture<Void> getItemFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程查询购物车选中的数据
            List<OrderItemVo> items = cartFeignService.getUserCartItems();
            confrimVo.setItem(items);
        }, executor).thenRunAsync(()->{
            //设置库存
            List<OrderItemVo> item = confrimVo.getItem();
            List<Long> IdList = item.stream().map(i -> i.getSkuId()).collect(Collectors.toList());
            R skusHasstock = wareFeginService.getSkusHasstock(IdList);
            List<SkuHasStockVo> stockVoList = (List<SkuHasStockVo>) skusHasstock.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if(stockVoList!=null){
                Map<Long, Boolean> stock = stockVoList.stream().collect(Collectors.toMap(k -> k.getSkuId(), v -> v.getHasStock()));
                confrimVo.setStocks(stock);
            }
        },executor);

        //保存用户的积分
        Integer integration = member.getIntegration();
        confrimVo.setIntegration(integration);
        //防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+member.getId(),token,30, TimeUnit.MINUTES);
        confrimVo.setOrderToken(token);
        //等待两个异步任务完成进行放行
        CompletableFuture.allOf(getAddressFuture,getItemFuture).get();
        return confrimVo;
    }

    @Override
    @Transactional
    public SubmitOrderResponseVo subimtOrder(OrderSubmitVo vo) {
        // 先将参数放到共享变量中，方便之后方法使用该参数
        threadLocal.set(vo);
        //下单 创建订单 验令牌 验价格 锁库存
        // 通过拦截器拿到用户的数据
        SubmitOrderResponseVo response=new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        response.setCode(0);
        String orderToken = vo.getOrderToken();
        // 验证令牌【令牌的对比和删除必须保证原子性】
        // 因此使用redis中脚本来进行验证并删除令牌
        // 0【删除失败/验证失败】 1【删除成功】
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if(result==0L){
            //令牌校验失败
            response.setCode(1);
            return response;
        }else { //令牌校验成功
            // 1 创建订单及订单项相关信息
            OrderCreateTo order = createOrder();
            // 2 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //金额对比成功

                //3 保存订单
                saveOrder(order);
                //4 库存锁定，只要有异常，回滚订单数据
                WareSkuLockVo lockVo=new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> itemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(itemVos);
                R r = wareFeginService.orderLockStocks(lockVo);
                if(r.getCode()==0){
                    //锁库存成功
                    response.setOrder(order.getOrder());
                    //订单创建成功后就发消息
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return response;
                }else {
                    //锁定失败
                    throw new NoStockException();
                }

            }else {
                //金额对比失败
                response.setCode(2);
                return response;
            }
        }
    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        OrderEntity one = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return one;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
            //关单之前查询当前订单状态
        OrderEntity order = this.getById(orderEntity.getId());
        if(order.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(order.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            //创建OrderTo
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            OrderTo to = new OrderTo();
            BeanUtils.copyProperties(order,to);

            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",to);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo vo = new PayVo();
        OrderEntity entity = this.getOrderStatus(orderSn);
        vo.setTotal_amount(entity.getPayAmount().setScale(2,BigDecimal.ROUND_UP).toString());
        vo.setOut_trade_no(orderSn);
        vo.setSubject("谷粒商城收银台捏");
        vo.setBody("欢迎下次光临");
        return vo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo member = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",member.getId()).orderByDesc("id")
        );
        List<OrderEntity> entities = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(list);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(entities);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public String handlePayResult(PayAsyncVo vo) {
        //保存订单流水
        PaymentInfoEntity info=new PaymentInfoEntity();
        info.setAlipayTradeNo(vo.getTrade_no());
        info.setOrderSn(vo.getOut_trade_no());
        info.setPaymentStatus(vo.getTrade_status());
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            info.setCallbackTime(format.parse(vo.getNotify_time()));
        } catch (ParseException e) {

        }

        paymentInfoService.save(info);
        //修改订单的状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            String orderSn=vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    @Transactional
    public void createSecKillOrder(SeckillOrderTo seckillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());

        orderItemService.save(orderItemEntity);
    }


    /**
     * 保存订单数据到数据库
     * @param order
     */
     public void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
         for (OrderItemEntity orderItem : orderItems) {
             orderItemService.save(orderItem);
         }

    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        //生成一个订单号
        String orderSn = IdWorker.getTimeId();
        // 1、构建订单
        OrderEntity entity = buildOrder(orderSn);
        // 2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = builderOrderItems(orderSn);
        // 3、设置价格相关信息
        computPrice(entity,itemEntities);
        createTo.setOrder(entity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    private void computPrice(OrderEntity entity, List<OrderItemEntity> itemEntities) {
        //订单的总额，叠加每一个订单项的总额
        BigDecimal total=new BigDecimal("0.0");
        //相关优惠信息
        // 优惠卷抵扣金额
        BigDecimal coupon = new BigDecimal("0");
        // 积分优惠金额
        BigDecimal integration = new BigDecimal("0");
        // 促销优惠金额
        BigDecimal promotion = new BigDecimal("0");
        // 积分
        BigDecimal gift = new BigDecimal("0");
        // 成长值
        BigDecimal growth = new BigDecimal("0");
        for (OrderItemEntity enity : itemEntities) {
            total=total.add(enity.getRealAmount());
            coupon=coupon.add(enity.getCouponAmount());
            integration=integration.add(enity.getIntegrationAmount());
            promotion=promotion.add(enity.getPromotionAmount());
            gift=gift.add(new BigDecimal(enity.getGiftIntegration().toString()));
            growth=growth.add(new BigDecimal(enity.getGiftGrowth().toString()));
        }
        //订单总额
        entity.setTotalAmount(total);
        //应付总额
        entity.setPayAmount(total.add(entity.getFreightAmount()));

        entity.setPromotionAmount(promotion);
        entity.setCouponAmount(coupon);
        entity.setIntegrationAmount(integration);

        //设置积分等相关信息
        entity.setIntegration(gift.intValue());
        entity.setGrowth(growth.intValue());

        entity.setDeleteStatus(0);

    }

    /**
     * 构建订单
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity=new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberRespVo.getId());
        OrderSubmitVo vo = threadLocal.get();
        R fare = wareFeginService.fare(vo.getAddrId());
        FareVo fareVo = (FareVo) fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费
        entity.setFreightAmount(fareVo.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareVo.getAddress().getCity());
        entity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        entity.setReceiverName(fareVo.getAddress().getName());
        entity.setReceiverPhone(fareVo.getAddress().getPhone());
        entity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        entity.setReceiverProvince(fareVo.getAddress().getProvince());
        entity.setReceiverRegion(fareVo.getAddress().getRegion());

        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建所有订单项
     * @return
     */
    private List<OrderItemEntity> builderOrderItems(String orderSn) {
        List<OrderItemVo> items = cartFeignService.getUserCartItems();
        if(items!=null&&items.size()>0){
            List<OrderItemEntity> itemEntities = items.stream().map(i -> {
                OrderItemEntity itemEntity =builderOrderItem(i);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建每一个订单项
     * @param vo
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo vo) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        // 1、根据skuid查询关联的spuinfo信息
        Long skuId = vo.getSkuId();
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo=(SpuInfoVo) spuInfo.getData(new TypeReference<SpuInfoVo>(){});
        // 2、设置商品项spu信息
        itemEntity.setSpuId(spuInfoVo.getId());
        itemEntity.setSpuName(spuInfoVo.getSpuName());
        itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        // 3、设置商品sku信息
        itemEntity.setSkuId(vo.getSkuId());
        itemEntity.setSkuName(vo.getTitle());
        itemEntity.setSkuPic(vo.getImage());
        itemEntity.setSkuQuantity(vo.getCount());
        String skuAttr = StringUtils.collectionToDelimitedString(vo.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuPrice(vo.getPrice());
        // 4、设置商品优惠信息【不做】
        // 5、设置商品积分信息
        itemEntity.setGiftGrowth(vo.getPrice().multiply(new BigDecimal(vo.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(vo.getPrice().multiply(new BigDecimal(vo.getCount().toString())).intValue());
        // 6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal realAmount = origin.subtract(itemEntity.getPromotionAmount()).
                subtract(itemEntity.getCouponAmount()).
                subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(realAmount);
        return itemEntity;
    }

}